package com.wx.plugin.mvc;

import com.wx.plugin.context.ThreadContext;
import com.wx.plugin.mp.core.WechatKernelExtend;
import io.github.elkan1788.mpsdk4j.core.WechatHandler;
import io.github.elkan1788.mpsdk4j.vo.MPAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Controller
@Slf4j
public class WXController {

    protected static WechatKernelExtend _wk = new WechatKernelExtend();

    @Autowired
    private MPAccount mpAccount;

    @Autowired
    private WechatHandler wechatHandler;

    public void init() {
        log.info("====== 微信请求发起 =======");
        _wk.setMpAct(mpAccount);
        _wk.setWechatHandler(wechatHandler);
    }

    @RequestMapping("/channel")
    public void wechatCore(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        this.interact(req, resp);
        ThreadContext.setHttp(req, resp);
    }

    /**
     * 与微信服务器互动
     *
     * <pre/>
     * !!!实际生产中写个入口方法调用即可!!!
     *
     * @param req
     *            微信服务器请求
     * @param resp
     *            响应微信服务器
     * @throws IOException
     */
    protected void interact(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        init();
        _wk.setParams(req.getParameterMap());
        String respmsg = "success";
        if ("GET".equals(req.getMethod())) {
            respmsg = _wk.check();
        }
        else {
            respmsg = _wk.handle(req.getInputStream());
        }
        // 输出回复消息
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        resp.getWriter().print(respmsg);
    }

//    @RequestMapping("/channel")
//    @ResponseBody
//    String channel(HttpServletRequest request, HttpServletResponse response) {
//        try {
//            log.info(HTTPUtil.showParamsString(request, CharConstant.NEW_LINE_CHAR));
//            request.setCharacterEncoding(EncodingConstant.UTF8);
//            response.setCharacterEncoding(EncodingConstant.UTF8);
//            InputStreamReader isr = new InputStreamReader(request.getInputStream(), EncodingConstant.UTF8);
//            String signature = request.getParameter("signature");
//            String echostr = request.getParameter("echostr");
//            String timestamp = request.getParameter("timestamp");
//            String nonce = request.getParameter("nonce");
//            if(StringUtils.isEmpty(signature) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(nonce)){
//                return "un raw request args:" + signature + echostr + timestamp + nonce;
//            }
//            String[] str = { MPConfig.CHANNEL_TOKEN, timestamp, nonce };
//            Arrays.sort(str);
//            String bigStr = str[0] + str[1] + str[2];
//            String digest = DigestUtil.sha1(bigStr);
//            if (digest.equals(signature)) {
//                SAXReader reader = new SAXReader();
//                reader.setEncoding(EncodingConstant.UTF8);
//                Document document = reader.read(isr);
//                document.setXMLEncoding(EncodingConstant.UTF8);
//                Map<String, Object> args = XmlUtil.dom2Map(document);
//                log.info(CharConstant.NEW_LINE_CHAR + CollectionUtil.mapToString(args, CharConstant.NEW_LINE_CHAR));
//
//                // do service
//                // ---
//                // ---
//
//                if(!StringUtils.isEmpty(echostr)){
//                    return echostr;
//                }else{
//                    return CharConstant.SUCCESS_STRING;
//                }
//            }
//            return "un raw request channel";
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage(), e);
//        }
//    }


}
